﻿namespace GameOn.Web.Entities
{
    /// <summary>
    /// This partial adds extended Match properties
    /// </summary>
    public partial class Match
    {
        private Player _loser;

        /// <summary>
        ///   Returns a string representation of the result of this Match
        /// </summary>
        public string Result
        {
            get { return GetMatchResult(); }
        }

        /// <summary>
        ///   Returns the loser of this match
        /// </summary>
        /// <remarks>
        ///   Loser is calculated and cached the first time this property is called
        /// </remarks>
        public Player Loser
        {
            get { return _loser ?? (_loser = GetLoser()); }
        }

        private Player GetLoser()
        {
            if (Winner == null) return null;
            if (Winner == Player1) return Player2;
            return Player1;
        }

        private string GetMatchResult()
        {
            string result = string.IsNullOrWhiteSpace(Score) ? string.Format("{0} won.", Winner) : string.Format("{0} won {1}.", Winner, Score);
            return result;
        }

        /// <summary>
        /// Enforces rules to ensure this entity is saved in an invariant state
        /// </summary>
        public void EnforceInvariants()
        {
            if (Player1 == Player2) throw new System.InvalidOperationException("Cannot create a Match where both players are the same");
        }
    }
}